const router = require('koa-router')()
const uploader = require('../uploader')
const mongoose = require('mongoose')
const path = require('path')
const fs = require('fs')
const util = require('util')
const stats = require('../helpers/stats')
const popular = require('../helpers/images')
const newestComments = require('../helpers/comments')

const rename = util.promisify(fs.rename)
const unlink = util.promisify(fs.unlink)

router.prefix('/images')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')

router.post('/', uploader.single('file'), async function(ctx, next){
      let file = ctx.req.file
      let diskFilename = file.filename + path.extname(file.originalname)
      await rename(file.path, path.dirname(file.path) + '/' + diskFilename)
        .then(() => Image.create({
      title: ctx.req.body.title,
      description: ctx.req.body.description,
      filename: diskFilename,
      mimetype: ctx.req.file.mimetype,
      originalName: ctx.req.file.originalname
    }))
      .then(doc => ctx.response.redirect('/images/' + doc.id))
      .catch(err => ctx.throw(500, err))
})

router.get('/:imageid', async function(ctx, next){
    let image = await Image.findById(ctx.params.imageid)
    image.views = image.views + 1
    await image.save()

    await Promise.all([
        stats(),
        popular(),
        Comment.find({image_id: ctx.params.imageid}),
        newestComments()
    ])
    .then( ([stats, popular, comments, newestComments]) => ctx.render('image',
        {image, stats, popular, comments, newestComments}
    ))
    .catch(err => ctx.throw(500, err))
})

router.post('/:imageid/like', async function(ctx, next){
    await Image.findById(ctx.params.imageid)
    .then(image => {
        image.likes = image.likes + 1
        image.save()
        return image
      })
    .then( image => ctx.body = {likes: image.likes})
    .catch(err => ctx.throw(500, err))
  })

router.delete('/:imageid', async (ctx,next) =>{
    let image = await Image.findById(ctx.params.imageid)
    await unlink(path.resolve('./public/upload/' + image.filename))
    .then( () => Image.deleteOne({_id: ctx.params.imageid}))
    .then( () => Comment.deleteMany({image_id : ctx.params.imageid}))
    .then( () => ctx.body = {res: true})
    .catch( err => ctx.throw(500,err) )
})

module.exports = router
